package com.benyi.byiee.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.benyi.byiee.constants.Status;
import com.benyi.byiee.dao.mappers.ProductClassifyMapper;
import com.benyi.byiee.model.db.ProductClassify;
import com.benyi.util.bean.ServiceException;

@Service
public class ProductClassifyService {
	private static Logger log = LoggerFactory.getLogger(ProductClassifyService.class);
	
	@Autowired
	ProductClassifyMapper productMapper;
	
	public List<ProductClassify>  queryList(String code){
		if(code !=null && code.length()>=1) {
			code = code.substring(0,1)+"%";
		}else {
			code="%";
		} 
		List<ProductClassify> list = productMapper.queryList(code);
		return list;
	}
	
	public ProductClassify save(ProductClassify v) throws ServiceException {
		String code = v.getPcode();
		if(code==null || code.length()==0) {
			throw new ServiceException("null_code","Code can not be null");
		} 
		if( v.getStatus()==null || !( v.getStatus() == Status.INVALID || v.getStatus() == Status.VALID) ) {
			v.setStatus(Status.INVALID);
		}
		ProductClassify c = productMapper.selectByPrimaryKey(v.getPcode()); 
		try {
			if(c==null) {
				productMapper.insert(v);
			}else {
				productMapper.updateByPrimaryKey(v);
			} 
			c = productMapper.selectByPrimaryKey(v.getPcode());
			return c;
		}catch(Exception e) {
			log.info("Exception", e);
			throw new ServiceException("save-exception",e.getMessage());
		} 
	}
	
	public int delete(ProductClassify v) throws ServiceException { 
		try { 
			int r = productMapper.deleteByPrimaryKey(v.getPcode());  
			return r; 
		}catch(Exception e) {
			log.info("Exception", e);
			throw new ServiceException("cannot_remove",e.getMessage());
		} 
	}
	
	public ProductClassify selectByCode(String code) {  
		ProductClassify c = productMapper.selectByPrimaryKey(code);  
		return c; 
	}
}
